﻿using System.Configuration;
using Autofac;
using Quartz.Impl;
using Quartz;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using Module = Autofac.Module;

namespace WinformDevelopFrame.Core.Autofac
{
    public class AutofacModuleRegister: Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            var dataAccess = Assembly.GetExecutingAssembly();
            #region 带有接口层的服务注入
            builder.RegisterAssemblyTypes(dataAccess)
                .Where(t => t.Name.EndsWith("Repository"))
                .AsImplementedInterfaces().InstancePerDependency()
                .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);
            builder.RegisterAssemblyTypes(dataAccess)
                .Where(t => t.Name.EndsWith("Service"))
                .AsImplementedInterfaces().InstancePerDependency()
                .PropertiesAutowired(PropertyWiringOptions.AllowCircularDependencies);
            #endregion

            #region 注册界面
            //获取所有窗体类型
            var baseType = typeof(System.Windows.Forms.Form);
            builder.RegisterAssemblyTypes(typeof(Program).Assembly)
                .Where(t => baseType.IsAssignableFrom(t) && t != baseType).AsImplementedInterfaces()
                .InstancePerDependency()
                .Named(t => t.Name, typeof(System.Windows.Forms.Form));
            var dlls = ConfigurationManager.AppSettings["FormDll"].Split(";");
            foreach (var dll in dlls)
            {
                var d = Assembly.LoadFrom(Application.StartupPath + dll);
                builder.RegisterAssemblyTypes(d)
                    .Where(t => baseType.IsAssignableFrom(t) && t != baseType).AsImplementedInterfaces()
                    .InstancePerDependency()
                    .Named(t => t.Name, typeof(System.Windows.Forms.Form));
            }
            #endregion
        }
    }
}
